import 'package:fish_redux/fish_redux.dart';

import 'action.dart';
import 'item/state.dart';
import 'state.dart';

Reducer<ClassListState> buildReducer() {
  return asReducer(
    <Object, Reducer<ClassListState>>{
      ClassListAction.listResult: _listResult,
      ClassListAction.loading: _loading,
      ClassListAction.loaded: _loaded,
      ClassListAction.deleted: _deleted,
    },
  );
}

ClassListState _loading(ClassListState state, Action action) {
  return state.clone()..isLoading = true;
}

ClassListState _loaded(ClassListState state, Action action) {
  final ClassListState newState = state.clone()..isLoading = false;
  return newState;
}

ClassListState _listResult(ClassListState state, Action action) {
  final Map<String, dynamic> data = action.payload;
  if (data == null) {
    return state;
  }

  final ClassListState newState = state.clone();
  newState.items = data['items'];

  return newState;
}

ClassListState _deleted(ClassListState state, Action action) {
  String code = action.payload;
  final ClassListState newState = state.clone();
  newState.items.removeWhere((ClassState state) => state.id == code);
  return newState;
}
